package net.core.common;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang.StringUtils;

public class StrUtils {
	
	/*
	 * 判断对象是否为空，非空返回false； 空或NULL返回true
	 */
	public static boolean isNull(Object obj) {
		if ( obj == null || "".equals(obj) || "null".equalsIgnoreCase((String) obj) ) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isNotNull(Object obj) {
		if ( obj == null || "".equals(obj) || "null".equalsIgnoreCase((String) obj) ) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 对象若为空返回,则空字符串。
	 * @param obj
	 * @return
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-7-26 上午11:48:29
	 */
	public static String getNotNullStrValue(Object obj) {
		if (obj == null) {
			return "";
		} else {
			Object objValue=obj;
			String value;
			if(objValue instanceof java.sql.Timestamp){
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				value = formatter.format(new Date(((java.sql.Timestamp)objValue).getTime()));
			}else {
				value=objValue.toString();
			}
			return value;
		}
	}
	public static String getNotNullStrValue(Object obj,String defV) {
		if (obj == null) {
			return defV;
		} else {
			return getNotNullStrValue(obj.toString(),defV);
		}
	}
	/**
	 * 对字符串为null，则返回空字符串。
	 * @param str 源字符串
	 * @return
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-7-26 上午11:50:28
	 */
	public static String getNotNullStrValue(String str) {
		if (str == null) {
			return "";
		} else {
			return getNotNullStrValue(str, "");
		}
	}
	/**
	 * 根据字符串是否为空，若为空的话返回默认字符串。
	 * @param str  源字符串
	 * @param defStr 默认字符串
	 * @return
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-7-26 上午11:48:50
	 */
	public static String getNotNullStrValue(String str, String defStr) {
		if (StringUtils.isNotEmpty(str) && !str.trim().equals(""))
			return str.trim();
		return defStr;
	}
	
	/**
	 * 字符串替换方法 忽略大小写
	 * @param source  原字符串
	 * @param oldStr  需要被替换的字符串
	 * @param newStr  需要替换成的新字符串
	 * @return
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-7-26 上午11:46:10
	 */
	public String replaceIgnoreCase(String source, String oldStr, String newStr) {
		if(source!=null){
			source = source.replaceAll("(?i)" + oldStr, newStr); 
		}
		return source;
	}
	
	/**
	 * @Title: 特殊字符转义，对于带'a'的字符进行转换，转换为''a''
	 * @param code
	 * @return
	 * @throws Exception
	 * @return String
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update 2012-8-4 下午03:52:08
	 */
    public static String peculiarCode(String code) {
        if (code != null) {
            code = code.replaceAll("'", "''");
        }
        return code;
    }
    /**
     * REC_ID 生成方法 前缀+ new
     * @Title: generateRecId
     * @param prefix 前缀
     * @return
     * @return String
     * @description 
     * @version 1.0
     * @author xiaowei
     * @update 2012-8-5 上午11:41:22
     */
    public static String generateRecId(String prefix) {
    	if(prefix!=null){
    		return prefix+new Date().getTime();
    	}else{
    		return ""+new Date().getTime();
    	}
    }
    
    public static int getNotNullIntValue(String str) {
		int intNum = 0;
		try {
			intNum = Integer.parseInt(str);
		} catch (NumberFormatException numForExc) {
			intNum = 0;
		}
		return intNum;
	}

	public static int getNotNullIntValue(String str, int defValue) {
		int intNum = getNotNullIntValue(str);
		if (intNum == 0){
			if(!"0".equals(str)){//如果传入字符串是0的话则不使用默认值
				intNum = defValue;
			}
		}
		return intNum;
	}
	

	public static String getNullStrToZero(String str) {
		return getNotNullStrValue(str, "0");
	}
	
	public static String filterXml(String value) {
		if (value == null)
			return null;
		char content[] = new char[value.length()];
		value.getChars(0, value.length(), content, 0);
		StringBuffer result = new StringBuffer(content.length + 50);
		for (int i = 0; i < content.length; i++)
			switch (content[i]) {
			case 60: // '<'
				result.append("&lt;");
				break;
			case 62: // '>'
				result.append("&gt;");
				break;
			case 38: // '&'
				result.append("&amp;");
				break;
			case 34: // '"'
				result.append("&quot;");
				break;
			case 39: // '\''
				result.append("&#39;");
				break;
			default:
				result.append(content[i]);
				break;
			}
		return result.toString();
	}
	
	/**
	 * 
	 * Description: 去掉字符串的下划线
	 * 
	 * @Title: getNotLineStr
	 * @param str
	 * @return String
	 * @author zyfine
	 * @date Oct 10, 2010
	 * 
	 */
	public static String getNotLineStr(String str) {
		String result = "";
		char s[] = str.toCharArray();
		if (s.length > 0) {
			for (int i = 0; i < s.length; i++) {
				if ('_' != s[i]) {
					result += s[i];
				}
			}
		}
		return result;
	}
	
	/*
	 * 特殊字符串转义  html
	 */
	public static String filtrateStringToHtml(String str) {
		try {
			if ((str != null) && (!str.trim().equals(""))) {
				str = str.replaceAll("&", "&amp;"); // &号
				str = str.replaceAll("\"", "&quot;"); // "号
				str = str.replaceAll("<", "&lt;"); // 正括号
				str = str.replaceAll(">", "&gt;"); // 反括号
				str = str.replaceAll("\n", "<br>"); // 回车
				str = str.replaceAll(" ", "&nbsp;"); // 空格
				str = str.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); // TAB键
			}
			return str;
		} catch (Exception e) {
			return "";
		}
	}
	
	/*
	 * html特殊字符串转义
	 */
	public static String filtrateHtmlToString(String str) {
		try {
			if ((str != null) && (!str.trim().equals(""))) {
				str = str.replaceAll("&amp;", "&"); // &号
				str = str.replaceAll("&quot;", "\""); // "号
				str = str.replaceAll("&lt;", "<"); // 正括号
				str = str.replaceAll("&gt;", ">"); // 反括号
				str = str.replaceAll("<br>", "\n"); // 回车
				str = str.replaceAll("&nbsp;", " "); // 空格
				str = str.replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "\t"); // TAB键
			}
			return str;
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 截取指定长度字符串,并替换尾字符
	 * @Title: substring 
	 * @param str 字符串
	 * @param toCount 长度
	 * @param more 替换符号
	 * @return
	 * @return String
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update Sep 14, 2012 5:40:21 PM
	 */
	public static String substring(String str, int toCount, String more) {
		int reInt = 0;
		String reStr = "";
		if (str == null) {
			return "";
		}
		char tempChar[] = str.toCharArray();
		if (more != null) {
			toCount -= more.length();
		}
		for (int kk = 0; kk < tempChar.length && toCount > reInt; kk++) {
			String s1 = String.valueOf(tempChar[kk]);
			byte b[] = s1.getBytes();
			reInt += b.length;
			reStr = (new StringBuilder(String.valueOf(reStr))).append(tempChar[kk]).toString();
		}

		if (toCount == reInt || toCount == reInt - 1) {
			reStr = (new StringBuilder(String.valueOf(reStr))).append(more).toString();
		}
		return reStr;
	}
	
	/**
	 * 字符串编码
	 * @Title: encoderStr
	 * @param str
	 * @param type
	 * @return
	 * @return String
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update Oct 15, 2012 2:47:21 PM
	 */
	public static String encoderStr(String str,String type){
		String resultStr = "";
		try{
			resultStr = URLEncoder.encode(str,type);
		}catch (Exception e) {
			System.out.println("字符串加密失败!!");
		}
		return resultStr;
	}
	
	public static String encoderStringDefault(String str){
		return encoderStr(str,Constants.SYS_ENCODE);
	}
	
	/**
	 * 字符串解码
	 * @Title: decoderStr
	 * @param str 源字符串
	 * @param type 解码编码
	 * @return
	 * @return String
	 * @description 
	 * @version 1.0
	 * @author xiaowei
	 * @update Oct 12, 2012 2:46:06 PM
	 */
	public static String decoderStr(String str,String type){
		String resultStr = "";
		try{
			resultStr = URLDecoder.decode(str,type);
		}catch (Exception e) {
			System.out.println("字符串解码失败!!");
		}
		return resultStr;
	}
	
	//使用系统默认编码解码
	public static String decoderStringDefault(String str){
		return decoderStr(str,Constants.SYS_ENCODE);
	}
	
	/**
	 * 字符串UTF-8编码转换
	 * @param s
	 * @return String
	 */
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("UTF-8");
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
	public static boolean checkStr(String regex,String str) {
        return Pattern.matches(regex, str); 
    } 
	
	//获取大写字符串
	public static String getStrToUpperCase(String str) {
		if (str == null) {
			return "";
		} else {
			return getNotNullStrValue(str, "").toUpperCase();
		}
	}
	
	/**
	 * 将字符串数组用引号包装，
	 * 例，"1,2,3"-->"'1','2','3'"
	 * @param value
	 * @param sp
	 * @param regex
	 * @return
	 */
	public static String getStrWithQuot(String value, String sp,String regex) {
		String[] arrValue = value.split(regex);
		String strResult = "";
		for (String str : arrValue) {
			strResult += regex + sp + str + sp;
		}
		strResult = strResult.substring(1);
		return strResult;
	}
	
	/**
	 * 判断文件是否是图片格式
	 * @param name
	 * @return
	 */
	public static boolean isImage(String name) {
		boolean result = false;
		String[] type = { ".JPG", ".GIF", ".BMP", ".PNG" };
		for (int i = 0; i < type.length; i++) {
			if (name.toUpperCase().indexOf(type[i]) != -1) {
				result = true;
				break;
			}
		}
		return result;
	}
	
	//测试main方法
	public static void main(String args[]) {
		System.out.println(toUtf8String("i'am shen li wei我是申立伟shenlw"));
		System.out.println(checkStr("^\\[.*\\]$", "[listId]"));//以[开头以  ]结尾
		System.out.println("[listId]".replace("[", "").replace("]", ""));
	}

	/**
	 * 从字符数组中移除指定的内容
	 * 例如："12,13,14,15"--{12,14}-->"13,15"
	 * @param fileId
	 * @param delId
	 * @return
	 */
	public static String getStrMove(String fileId, String[] delId) {
		if (fileId == null || fileId.equals("")) {
			return "";
		}
		if (delId == null || delId.length == 0) {
			return fileId;
		}
		String[] strArr = fileId.split(",");
		boolean bool = false;
		String r = "";
		for (String s : strArr) {
			for (String t : delId) {
				bool = s.equals(t);
				if (bool) {
					break;
				}
			}
			if (!bool) {
				r += "," + s;
			}
		}
		r = r.substring(1);
		return r;
	}

	public static String transArrayToString(String[] arr) {
		if(null==arr){
			return null;
		}
		String result="";
		for(int i=0;i<arr.length;i++){
			result+=","+arr[i];
		}
		// TODO Auto-generated method stub
		return result.substring(1);
	}
}
